<template>
	<div class="login-container">
		<video class="video"
			muted
			src="../../assets/video/bg-video.mp4"
			loop="loop"
			autoplay="true"></video>

		<div class="bg2"></div>

		<el-form :model="loginForm"
			status-icon
			:rules="rules"
			ref="loginForm"
			label-width="100px"
			class="login-loginForm">
			<h1 class="title">crm管理系统</h1>
			<!-- 电脑角标 -->
			<i @click="isErweiLogin = !isErweiLogin"
				:class="[
          'jiaobiao',
          'iconfont',
          isErweiLogin ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"></i>
			<!-- 常规登入 -->
			<div class="common-login"
				v-if="!isErweiLogin">
				<el-form-item label="用户名"
					prop="username">
					<el-input type="text"
						v-model="loginForm.username"
						autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="密码"
					prop="password">
					<el-input type="password"
						v-model="loginForm.password"
						autocomplete="off"></el-input>
				</el-form-item>

				<el-form-item label="验证码"
					prop="captcha">
					<el-input maxlength="5"
						@keydown.native.13="submitForm('loginForm')"
						v-model="loginForm.captcha"
						class="captcha"
						ref="captcha"></el-input>
					<span class="captcha-svg"
						v-html="captchaSvg"
						@click="fetchCaptcha"></span>
				</el-form-item>

				<el-form-item>
					<el-button type="primary"
						@click="submitForm('loginForm')">登入</el-button>
				</el-form-item>
			</div>
			<!-- 切换二维码登入 -->
			<div class="erwei"
				v-else>
				<div class="img">
					<img width="200px"
						:src="qrDataUrl"
						alt="" />
					<i class="mask"
						:style="qrStyle"
						@click="getQrcode"
						v-show="isScanCodeSuccess"> </i>
				</div>
				<!-- <p v-text="qrtip">请使用手机微信扫码登入</p> -->
			</div>
		</el-form>
	</div>
</template>
<script>
	import * as userApi from "../../api/users";
	import { mapMutations } from "vuex";
	import io from "socket.io-client"
	import qrcode from "qrcode"
	//引入图片
	import codeSuccessImg from "../../assets/img/scancode.png"
	import codeInvalidImg from "../../assets/img/invalidQr.png"
	//校验函数
	var validateCaptcha = (rule, value, callback) => {
		// console.log(rule)

		if (!value) {
			callback("验证码输入为空");
		} else {
			callback();
		}
	};
	var validateUsername = (rule, value, callback) => {
		// console.log(value) 表单的输入值
		// callback('fsdfdsf') 传入了参数 说明表单校验不通过 不传参数 说明表单校验通过
		//用户名正则，3到16位（字母，数字，下划线，减号）
		var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
		if (uPattern.test(value)) {
			//校验通过
			callback();
		} else {
			callback("3到16位（字母，数字，下划线，减号）");
		}
	};
	var validatePassword = (rule, value, callback) => {
		if (!value) {
			callback("密码不能输入为空");
		} else {
			callback();
		}
	};
	export default {
		data() {
			return {
				isErweiLogin: false,//默认不是二维码登入
				qrDataUrl: "",//二维码图片地址
				isScanCodeSuccess: false,//是否扫描二维码成功
				qrStyle: {},//二维码遮罩样式的初始值
				captchaSvg: "",
				loginForm: {
					username: "",
					password: "",
					captcha: "",
				},
				rules: {
					username: [{ validator: validateUsername, trigger: "blur" }],
					password: [{ validator: validatePassword, trigger: "blur" }],
					captcha: [{ validator: validateCaptcha, trigger: "blur" }],
				},
			};
		},
		created() {
			//在created这个钩子函数中获取验证码
			this.fetchCaptcha();
		},
		methods: {
			//映射vuex的方法
			...mapMutations(["SET_USERINFO"]),
			//封装一个方法,专门用户获取验证码
			fetchCaptcha() {
				userApi.getCaptchaApi().then((res) => {
					// console.log(res)
					this.captchaSvg = res.data.img;
				});
			},
			submitForm(formName) {
				//验证本地表单校验是否成功
				this.$refs[formName].validate((valid, unpass) => {
					if (valid) {
						//本地表单校验通过
						//这里可以发送登入请求

						//首先需要发送请求,校验验证码是否正确,如果正确,那么可以继续发送登入请求
						let { username, password, captcha } = this.loginForm; //将loginForm中的属性解构出来
						// console.log(captcha.toLowerCase())
						userApi.verifyCaptchaApi(captcha.toLowerCase()).then((res) => {
							// console.log("====",res)
							//新语法 可链入
							//res是不是undefined如果不是继续.data 如果是那就不往后链入data了
							if (res?.data?.state) {
								//验证码通过了
								//发送登入请求,进行登入
								userApi.loginApi({ username, password }).then((res) => {
									// console.log(res)
									if (res.data.state) {
										// 登入成功之后要做什么

										// this.$store.dispatch("FETCH_MENULIST")

										//res.data.userInfo包含了当前登入用户的信息,这个些信息肯定会被以后的组件共享
										//所以可以放到vuex中
										this.SET_USERINFO(res.data.userInfo);
										//跳转之前 将用户的信息存储到本地
										//token也要存到本地
										localStorage.setItem("yf-token", res.data.token);
										localStorage.setItem("crm-userInfo", JSON.stringify(res.data.userInfo));
										//页面需要进行跳转
										this.$router.push("/");
									}
								});
							} else {
								// alert('验证码错误')
								//验证码错误 清空验证码 刷新验证码 也要让这个输入框获焦点
								this.loginForm.captcha = "";
								this.fetchCaptcha();
								// console.log(this.$refs.captcha)
								this.$refs.captcha.focus();
							}
						});
						//如果不正确 需要有错误提示

						// console.log(this.loginForm)
						// let { username, password } = this.loginForm;
						// userApi.loginApi({ username, password })
						// 	.then(res => {
						// 		console.log(res)
						// 	})
					} else {
						//不通过
					}
				});
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},

			//封装一个方法专门用于获取二维码

			async getQrcode() {
				//对遮罩样式初始化
				this.isScanCodeSuccess =false;
				//从本地取出sid
				let sid = localStorage.getItem('yf-sid')
				//请求接口获取二维码url
				let res = await userApi.getQrcodeApi(sid);
				// console.log(res)
				//解构出来二维码Url
				let { scanCodeUrl } = res.data;
				console.log(scanCodeUrl)
				//通过qrcode这个插件 将地址转换成为二维码图片
				this.qrDataUrl = await qrcode.toDataURL(scanCodeUrl);
				// console.log(erweiImg)
			}
		},
		//数据监听
		watch: {
			//监听是否二维码登入
			isErweiLogin(newVal) {
				//如果newVal是true 表示就是微信扫码登入
				if (newVal) {
					//建立socket连接
					let socket = io("wss://chst.vip");

					//监听连接成功事件

					socket.on("connectSuccess", async data => {
						// console.log(sid)
						//解构sid
						let { sid } = data;
						//存到本地
						localStorage.setItem("yf-sid", sid)

						this.getQrcode()

					})

					//监听扫码成功的事件
					socket.on('scancodeSuccess', async data => {
						//显示遮罩
						this.isScanCodeSuccess = true;
						this.qrStyle = {
							backgroundImage: `url(${codeSuccessImg})`
						}
						// console.log(this.qrStyle)
						// console.log(data)
						let { wechatCode } = data;

						//发起登入请求
						let res = await userApi.wechatLoginApi(wechatCode);
						console.log(res)
						//解构属性
						let { token, userInfo } = res.data;

						//将token存到本地
						localStorage.setItem('yf-token', token)
						//userInfo也存到本地
						localStorage.setItem('userInfo', JSON.stringify(userInfo))
						//也要将userInfo设置到vuex

						//页面跳转
						this.$router.push('/')


					})

					//监听二维码失效的事件
					socket.on('invalidCode', data => {
						console.log(data)
						this.isScanCodeSuccess = true;
						this.qrStyle = {
							backgroundImage: `url(${codeInvalidImg})`
						}
					})
				}
			}
		}
	};
</script>
<style scoped lang="less">
//样式设置不上的情况,解决方案
//1.检查类名是否正确
//2.检查权重是否正确
//3.检查是否需要穿透

.login-container {
	text-align: center;
	color: #fff;
	.common-login {
		padding-right: 50px;
	}
	//二维码样式
	.erwei .img {
		display: inline-block;
		position: relative;
		width: 200px;
		height: 200px;
		img {
			position: absolute;
			left: 0;
		}
		.mask {
			width: 100%;
			height: 100%;
			opacity: 0.8;
			background-color: #fff;
			position: absolute;
			left: 0;
			// background-image: url("../../assets/img/scancode.png");
			background-size: 50%;
			background-repeat: no-repeat;
			background-position: center;
			cursor: pointer;
		}
	}
	.jiaobiao {
		font-size: 60px;
		color: #fff;
		position: absolute;
		right: -1px;
		top: -1px;
		cursor: pointer;
		opacity: 0.7;
	}
	.video {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}
	.bg2 {
		background-image: url("../../assets/img/bg2.png");
		background-repeat: no-repeat;
		position: fixed;
		width: 20%;
		height: 40%;
		background-size: 100% 100%;
		left: 20%;
		top: 40%;
		opacity: 0.5;
	}
	.el-form {
		position: fixed;
		right: 10%;
		top: 25%;
		border-radius: 5px;
		width: 400px;
		background-color: rgba(0, 0, 0, 0.3);
		padding: 100px 0 50px 0;
		/deep/ .el-input__inner {
			width: 250px;
		}
		/deep/ .el-button--primary {
			background: linear-gradient(90deg, #1596fb, #002dff);
			width: 250px;
		}
		/deep/ .el-form-item__label {
			color: #fff;
		}
		.title {
			margin: 0 0 60px 0;
			text-align: center;
			color: #fff;
		}
		/deep/ .captcha {
			width: 100px;
			vertical-align: top;
			.el-input__inner {
				width: 100%;
				height: 45px;
				border-radius: 5px 0 0 5px;
				border: 0;
				font-size: 18px;
			}
		}
		svg path {
			stroke: red;
		}
		.captcha-svg {
			background: #fff;
			display: inline-block;
			height: 45px;
			width: 150px;
			text-align: center;
			cursor: pointer;
			border: 0;
			border-radius: 0px 5px 5px 0;
		}
		.el-form-item__content {
			width: 250px !important;
		}
	}
}
</style>
